<?php

namespace  Helper;

use Swoole\Database\RedisConfig;
use Swoole\Database\RedisPool;
use Swoole\Timer;
use function Couchbase\basicDecoderV1;

class Redis1
{
    private static $pool;
    private static $config;

    public static function getInstance(){
        if(self::$pool){
            $redis  = self::$pool->get() ;
            defer(function ()use ($redis){
                self::$pool->put($redis);

            });
            var_dump('pop a conn!');

            return $redis;
        }else{

            self::$config =  Config::getInstance()->get('redis');
            self::$pool = new RedisPool((new RedisConfig())
                            ->withHost(self::$config['host'])
                            ->withPort(self::$config['port'])
                            ->withAuth(self::$config['auth'])
                            ->withDbIndex(1)
                            ->withTimeout(1),

                self::$config['POOL_MAX_NUM']
            );
            var_dump('create pool');
            //起个定时器清理无效的连接
//            Timer::tick(30*1000 ,self::clear());
            return  self::$pool->get();
        }
    }



    public static function clear(){

        $callback = function (){

            $poolLength = self::$pool->length();
            var_dump('开始清理');
            for ($i=0;$i< $poolLength;$i++){
                $res = self::$pool->pop()->ping();

                if($res != 0){
                    var_dump('清理了无效连接');
                    self::createConnect(1);

                }

            }
        };

        return $callback;

    }


}